package com.techstar.common.jackson;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.datatype.joda.cfg.FormatConfig;
import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat;
import com.fasterxml.jackson.datatype.joda.deser.JodaDateDeserializerBase;

public class DateDeserializer extends JodaDateDeserializerBase<Date> {
    private static final long serialVersionUID = 1L;
    private static final SimpleDateFormat FORMATTER_YYYYMMDD = new SimpleDateFormat("yyyyMMdd");
    private static final SimpleDateFormat FORMATTER_YYYY_MM_DD = new SimpleDateFormat("yyyy-MM-dd");
    private static final SimpleDateFormat FORMATTER_YYYYMMDDHH = new SimpleDateFormat("yyyyMMddHH");
    private static final SimpleDateFormat FORMATTER_YYYY_MM_DDHHmmss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public DateDeserializer() {
        this(FormatConfig.DEFAULT_LOCAL_DATEONLY_FORMAT);
    }

    public DateDeserializer(JacksonJodaDateFormat format) {
        super(Date.class, format);
    }

    public JodaDateDeserializerBase<?> withFormat(JacksonJodaDateFormat format) {
        return new com.fasterxml.jackson.datatype.joda.deser.LocalDateDeserializer(format);
    }

    public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        switch (p.getCurrentTokenId()) {
            case 4:
            case 5:
            case 6:
                String str = p.getText().trim();
                try {
                    switch (str.length()) {
                        case 8:
                            return FORMATTER_YYYYMMDD.parse(str);
                        case 10:
                            if (StringUtils.contains(str, "-")) {
                                return FORMATTER_YYYY_MM_DD.parse(str);
                            } else {
                                return FORMATTER_YYYYMMDDHH.parse(str);
                            }
                        case 19:
                            if (StringUtils.contains(str, "-")) {
                                return FORMATTER_YYYY_MM_DDHHmmss.parse(str);
                            }
                        default:
                            return null;
                    }
                } catch (ParseException e) {
                    return (Date) ctxt.handleUnexpectedToken(this.handledType(), p.getCurrentToken(), p, "expected String, Number or JSON Array", new Object[0]);
                }
            default:
                return (Date) ctxt.handleUnexpectedToken(this.handledType(), p.getCurrentToken(), p, "expected String, Number or JSON Array", new Object[0]);
        }
    }
    public static void main(String[] args) {
		String s = "2021-09-27 00:00:00";
		System.out.println(s.length());
	}
}
